<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">登录</h2>
      <el-form :model="loginForm"    label-width="80px" ref="ruleFormRef">
        <el-form-item label="用户名" prop="userName">
          <el-input  v-model="loginForm.userName" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="密码" prop="userPwd">
          <el-input  type="password" v-model="loginForm.userPwd" placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
          <el-input   v-model="loginForm.captcha" placeholder="请输入验证码" style="width: 80px"/>
           <img :src="CaptchaImage" alt="验证码" @click="GetCaptchaImage" width="140px" height="40px" style="cursor: pointer; margin-left: 10px"/>

        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="Verify">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref,onMounted,reactive } from 'vue';
import { ElMessage } from 'element-plus';
import axios from "axios"
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
const router = useRouter()
const loginForm = ref({
  userName: '',
  userPwd: '',
  captcha: ''
});
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()

const CaptchaImage=ref("")
onMounted(()=>{
   GetCaptchaImage()
})
//生成验证码
const GetCaptchaImage =  () => {
  

   axios.post('https://localhost:44392/api/Captchas/GenerateCaptcha',{},{responseType: 'arraybuffer'}).then(res=>{
const blob = new Blob([res.data], { type: 'image/jpeg' });

    const url = URL.createObjectURL(blob);
    CaptchaImage.value = url;
    console.log(CaptchaImage.value);
   })
    
 
};

//验证验证码
const Verify=async (formEl: FormInstance | undefined)=>{
  if(loginForm.value.captcha==""){
    ElMessage.error('请输入验证码')
    return
  }
       axios.delete("https://localhost:44392/api/app/delete-captcha/captcha",{
    params:{
      captcha:loginForm.value.captcha
    }
  }).then(res=>{
    if(res.data.isSuc){
      console.log(res.data.msg)
      handleLogin()
      return
    }else{
      ElMessage.error("验证码错误")
      return
    }
  })
}
//登录
const handleLogin = () => {
  axios.post('https://localhost:44392/api/app/login-services/login', loginForm.value)
    .then(res => {
     if(res.data.isSuc){
       console.log(res);
      ElMessage.success('登录成功');
      router.push('/Show')
     }
     else{
      ElMessage.error(res.data.msg);
     }
    })
    
};

</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
 
  background-image: url(https://picsum.photos/1920/1080);
}

.login-card {
  width: 400px;
  padding: 20px;
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
}
</style>